package com.lj.infoisland.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lj.infoisland.util.UniqueRandomStringGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Value("${USER_UNIQUE_ID}")
    private String USER_UNIQUE_ID;

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = Calendar.getInstance().getTime();
        this.fillStrategy(metaObject, "createTime", date);
        this.fillStrategy(metaObject, "updateTime", date);
        this.strictInsertFill(metaObject, "createdAt", Date.class, new Date());
        this.strictInsertFill(metaObject, "publishedAt", Date.class, new Date());
        this.strictInsertFill(metaObject, "updatedAt", Date.class, new Date());
        this.strictInsertFill(metaObject, "userUniqueId", String.class, USER_UNIQUE_ID + UniqueRandomStringGenerator.generateUniqueString());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = Calendar.getInstance().getTime();
        this.setFieldValByName("updateTime", date, metaObject);
        this.strictUpdateFill(metaObject, "updatedAt", Date.class, new Date());
    }
}